package com.dreamer.repository.lottery;

import com.dreamer.domain.lottery.Activity;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;
import ps.mx.otter.utils.SearchParameter;
import ps.mx.otter.utils.dao.hibernate.HibernateBaseDAO;

import java.util.List;

@Repository("activityDAO")
public class ActivityDAO extends HibernateBaseDAO<Activity> {

    private Session getCurrentSession() {
        return getSessionFactory().getCurrentSession();
    }

    public List<Activity> searchAllByPage(SearchParameter<Activity> p) {
        return super.searchEntityByPage(p, (t) -> {
            Example example = Example.create(t.getEntity()).enableLike(MatchMode.ANYWHERE);
            Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(getClazz());
            criteria.add(example);
            return criteria;
        }, (o)-> true);
    }

    public void save(Activity transientInstance) {

        try {
            getCurrentSession().save(transientInstance);

        } catch (RuntimeException re) {

            throw re;
        }
    }

    public void delete(Activity persistentInstance) {
        try {
            getCurrentSession().delete(persistentInstance);

        } catch (RuntimeException re) {

            throw re;
        }
    }

    public Activity findById(Integer id) {

        try {
            Activity instance = (Activity) getCurrentSession().get(
                    "com.dreamer.domain.lottery.Activity", id);
            return instance;
        } catch (RuntimeException re) {

            throw re;
        }
    }

    public Activity merge(Activity detachedInstance) {
        try {
            Activity result = (Activity) getCurrentSession().merge(detachedInstance);
            return result;
        } catch (RuntimeException re) {

            throw re;
        }
    }

    public List<Activity> findAll() {
        try {
            String queryString = "from Activity";
            Query queryObject = getCurrentSession().createQuery(queryString);
            return queryObject.list();
        } catch (RuntimeException re) {
            throw re;
        }
    }

}
